import { showImagePreview } from "vant"
import { VideoPlayer } from "./plugins"
import { ImagePreview as VanImagePreview, Overlay as VanOverlay, Icon as VanIcon } from 'vant';
import { createApp, defineComponent, ref, type CSSProperties } from 'vue'

export const previewImage = (src: string) => {
    showImagePreview({
        images: [src],
        startPosition: 0,
        loop: false,
        closeable: true
    })
}

export const previewImages = (srcs: string[], initLocal = 0) => {
    showImagePreview({
        images: srcs,
        startPosition: Math.min(initLocal, srcs.length - 1),
        loop: false,
        closeable: true
    })
}

export const previewVideo = (src: string, poster?: string) => {
    const closeStyle: CSSProperties = {
        position: 'absolute',
        top: '0',
        right: '0',
        padding: '16px',
        fontSize: '24px',
        color: '#c8c9cc'
    }

    const preview = defineComponent({
        setup() {
            const show = ref(true);
            const onClosed = () => {
                show.value = false;

                setTimeout(() => {
                    app.unmount();
                    previewDom.remove();
                }, 301);
            }

            return () => (
                <VanOverlay show={show.value} zIndex={100}>
                    {{
                        default: () => <div style={{ height: '100vh' }}>
                            <VideoPlayer src={src} poster={poster} style={{ height: '100%' }} />
                            <div style={closeStyle} onClick={onClosed}><VanIcon name="clear" /></div>
                        </div>
                    }}
                </VanOverlay>
            )
        }
    })

    const app = createApp(preview);
    const previewDom = document.createElement('div');
    document.body.append(previewDom);
    app.mount(previewDom);
}
